<script lang="ts" setup>
import { ElForm, ElTooltip } from 'element-plus'
import { ElValidator, passwordRule, phoneRule, required, usernameRule } from '@utils/form-rule'
import { registerUserAPI, sendNoteCodeAPI } from '@/api/system'
import Authorization from '@utils/authorization'
import { ref } from 'vue'
import { CountDownTimer } from '@/utils'

const router = useRouter()

onMounted(() => {
  Authorization.token && router.push({ name: 'BoardIndex' })
})

// region TODO 注册表单
const registerForm = ref({
  // 确认密码
  confirmPassword: '',
  // 姓名
  nickName: '',
  // 用户密码
  password: '',
  // 手机号
  phone: '',
  // 短信code
  smsCode: '',
  // 用户名
  username: ''
})
const registerFormRef = shallowRef<InstanceType<typeof ElForm>>()
const registerFormRules = ref({
  username: [required('请输入账号/手机号'), usernameRule],
  phone: [required('请输入手机号'), phoneRule],
  smsCode: [required('请输入验证码')],
  password: [required('请输入密码'), passwordRule],
  confirmPassword: [{
    validator (rule: any, value: any, callback: (error?: Error) => void) {
      const { password, confirmPassword } = registerForm.value
      callback(password === confirmPassword ? undefined : Error('两次密码不一致'))
    },
    trigger: 'blur',
    required: true
  } as ElValidator],
  nickName: [required('请输入姓名')]
})
// endregion

// region TODO 注册表单提交
function formSubmitHandle () {
  registerFormRef.value.validate().then(() => {
    if (!privacyCheckbox.value) {
      showPrivacy.value = true
      return
    }
    registerUserAPI(registerForm.value).then((res) => {
      res.result().then(() => {
        ElMessage.success('注册成功')
        router.replace({ name: 'Login' })
      })
    })
  })
}
// endregion

// region TODO 发送验证码
// 剩余倒计时
const remainingCountdown = ref(0)
const remainingCodeCountDownTimer = new CountDownTimer({
  key: 'registerAuth',
  toCookie: true,
  fn (e) {
    remainingCountdown.value = e
  }
})

// TODO 发送验证码
// 发送验证码
function sendVerificationCode () {
  registerFormRef.value.validateField(['phone']).then(() => {
    if (registerForm.value.phone) {
      const loading = ElLoading.service({ text: '正在发送...' })
      sendNoteCodeAPI({
        phone: registerForm.value.phone,
        type: 1
      }).then((res) => {
        res.result().then(() => {
          ElMessage.success('短信已发送，注意查收')
          remainingCodeCountDownTimer.run(60)
        })
      }).finally(loading.close)
    }
  })
}
// endregion

// region TODO 勾选隐私协议
const showPrivacy = shallowRef(false)
const privacyCheckbox = shallowRef(false)
function privacyCheckboxChangeHandle () {
  if (privacyCheckbox.value && showPrivacy.value) {
    showPrivacy.value = false
  }
}
// endregion

// region TODO 跳转
function toLogin () {
  router.replace({ name: 'Login' })
}
// endregion

</script>

<template>
  <div class="register-container d-flex-center">
    <!--表单容器-->
    <div class="form-container mt-20">
      <p class="text-center text-color-primary fs-20" style="padding-left: 80px;">注册账号</p>
      <!--注册表单-->
      <el-form
        ref="registerFormRef"
        class="mt-24"
        size="large"
        :model="registerForm" :rules="registerFormRules"
        label-width="80px"
        @submit.prevent="formSubmitHandle"
      >
        <el-form-item prop="username" label="用户名">
          <el-input v-model.trim="registerForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item prop="phone" label="手机号">
          <el-input v-model.trim="registerForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item prop="smsCode" label="验证码">
          <el-input v-model.trim="registerForm.smsCode" placeholder="请输入验证码">
            <template #append>
              <el-button :disabled="remainingCountdown > 0" style="width: 110px;" @click="sendVerificationCode">
                <span v-if="remainingCountdown">{{ remainingCountdown }}秒后重试</span>
                <span v-else class="color-primary">获取验证码</span>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input v-model.trim="registerForm.password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item prop="confirmPassword" label="确认密码">
          <el-input v-model.trim="registerForm.confirmPassword" placeholder="请确认密码" show-password />
        </el-form-item>
        <el-form-item prop="nickName" label="姓名">
          <el-input v-model.trim="registerForm.nickName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item>
          <div class="d-flex-center" style="line-height: 14px;height: 14px;">
            <el-tooltip
              :visible="showPrivacy" content="阅读并勾选后继续" placement="top"
              effect="dark"
              trigger="click"
            >
              <el-checkbox v-model="privacyCheckbox" class="mr-2" @change="privacyCheckboxChangeHandle" />
            </el-tooltip>
            <span class="fs-12 color-secondary">
              <span>阅读并同意</span>
              <el-link type="primary" href="/#/privacy" class="fs-12 mx-1 color-primary">服务协议</el-link>
              <span>和</span>
              <el-link type="primary" href="/#/privacy" class="fs-12 mx-1 color-primary">隐私政策</el-link>
            </span>
          </div>
        </el-form-item>
        <!--立即注册-->
        <el-form-item class="mb-0">
          <div class="wh-100">
            <el-button class="form_btn-submit" native-type="submit" type="primary">立即注册</el-button>
            <div class="fs-12 d-flex-center mt-28">
              <el-divider />
              <div style="white-space: nowrap" class="mx-12 color-secondary">
                <span>已有账号？</span>
                <el-link type="primary" class="d-inline vertical-align-top fs-12" @click="toLogin">立即登录</el-link>
              </div>
              <el-divider />
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <!--版权-->
    <div class="copyright">
      <div>
        <span>需要帮助？</span>
        <el-link type="primary" class="fs-12">联系客服<!--提示客服热线400-xxxx-xxxx--></el-link>
      </div>
      <div class="mt-8">Copyright © 2023 Yuankong Info All Rights Reserved</div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
//页面
.register-container {
  height: 100vh;
  min-height: 870px;
  background: url("./images/bg-login.png") top / 100% 100%;
  position: relative;
  > div {
    width: 596px;
  }
}
//表单
.form-container {
  padding: 40px 138px 40px 60px;
  width: 428px;
  height: fit-content;
  border-radius: 10px;
  background-color: white;
  //提交按钮
  .form_btn-submit {
    width: 100%;
    //--el-button-text-color: #FFFFFF;
    //--el-button-bg-color: var(--el-color-primary);
    //--el-button-hover-bg-color: var(--yk-color-primary-light-3);
    //--el-button-hover-text-color: #FFFFFF;
    font-size: 14px;
  }
  //输入框input前缀
  ::v-deep(.el-input__prefix) {
    font-size: 18px;
  }
}

// 版权
.copyright {
  color: var(--yk-color-secondary);
  position: absolute;
  inset: auto 0 40px 0;
  font-size: 12px;
  width: fit-content;
  margin: auto;
  text-align: center;
}
</style>
